package nettypro.netty.simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.util.CharsetUtil;

import java.nio.charset.CharsetDecoder;

/**
 * @ClassName NettyServerHandler
 * @Description TODO
 * @Author zeny
 * @Date 2020/3/23 0023 16:03
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.channel().eventLoop().execute(()->{
            try {
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端", CharsetUtil.UTF_8));
        });
        System.out.println("go on ...");
//        System.out.println("服务器读取线程: " + Thread.currentThread().getName());
//        System.out.println("server ctx = " + ctx);
//        Channel channel = ctx.channel();
//        ChannelPipeline pipeline = ctx.pipeline();
//        ByteBuf buf = (ByteBuf) msg;
//        System.out.println("客户端发送消息: " + buf.toString(CharsetUtil.UTF_8));
//        System.out.println("客户端地址: " + channel.remoteAddress());
    }

    /**
     * @Description 读取数据完毕
     * @Date 2020/3/23 0023 16:13
     * @param ctx
     * @return void
     **/
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端", CharsetUtil.UTF_8));
    }

    /**
     * @Description 处理异常
     * @Date 2020/3/23 0023 16:16
     * @param ctx
     * @param cause
     * @return void
     **/
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
